const rp = require('request-promise-native');
const program = require('commander');
const fs = require('mz/fs');

program.version('0.0.1')

program
  .command('upload <file>')
  .description('upload the file to endpoint')
  .option('-e, --endpoint <url>', 'explicit the server url', 'localhost:8888')
  .action(async function(file, options) {
    let fileExisted = await fs.exists(file);
    if (!fileExisted) {
      console.log(`can not find file: ${file}`);
      return;
    }
    console.log(`upload ${file} to ${options.endpoint}`);
    await upload(file, options.endpoint);
  })
  .on('--help', function() {
    console.log('Example');
    console.log('\tnode index.js upload ~/Desktop/somefile --endpoint localhost:3000');
  })

program.parse(process.argv);


async function upload(file, url) {
  try {
    var res = await rp.post('http://' + url, {
      formData: {
        file: fs.createReadStream(file)
      },
      json: true
    });
    console.log('ret: ', res.ret);
    console.log('file: ', res.file);
  } catch(e) {
    console.log(e);
  }
}

